<template>
  <div class="app-container">
    <div style="width: 70%; height: 600px ;float:left">
      <el-form ref="Form" :inline="true" :model="Form" :rules="Rules">
        <el-select v-model="value" placeholder="请选择" style="width: 100px">
          <el-option
            label="姓名"
            value="1"
          />
          <el-option
            label="工号"
            value="2"
          />
        </el-select>
        <el-form-item v-if="vis1" prop="name">
          <el-input v-model="Form.name" placeholder="请输入用户姓名" :validate-event="false" />
        </el-form-item>
        <el-form-item v-if="vis2" prop="uid">
          <el-input v-model="Form.uid" placeholder="请输入用户工号" :validate-event="false" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-button v-if="isShow1" type="primary" @click="getData">取消查询</el-button>
        <el-button type="primary" @click="handleImport">导入</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
      </el-form>
      <el-dialog
        title="导入Excel"
        :visible.sync="ImportDialog"
        width="30%"
        :before-close="handleClose"
      >
        <div
          style="margin-top: 30%"
        >
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="actionAddress"
            :auto-upload="false"
            :on-success="handlemessage"
            style="position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器
            </el-button>
            <div slot="tip" class="el-upload__tip">请上传想要导入的Excel文件</div>
          </el-upload>
        </div>
      </el-dialog>
      <el-dialog
        title="导出Excel"
        :visible.sync="ExportDialog"
        width="30%"
        :before-close="handleClose"
      >
        <div style="float: top">
          <div
            style="position:relative;top:10%;bottom:0;left: 0;
            margin: auto;right: 0;
            text-align:center"
          >
            <el-button type="primary" @click="handleExport1">导出所有数据</el-button>
            <el-button type="primary" @click="handleExport2">导出模板</el-button>
          </div>
          <div width="100%">
            <h3 style="text-align: center">你可以选择“导出模板”导出一张空白Excel</h3>
          </div>
        </div>
      </el-dialog>
      <el-table
        stripe
        border
        height="550"
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{'text-align': 'center'}"
      >
        <el-table-column
          prop="name"
          label="姓名"
          width="150"
          align="center"
        />
        <el-table-column
          prop="uid"
          label="工号"
          width="150"
          align="center"
        />
        <el-table-column
          prop="roles"
          label="角色"
          align="center"
        />
        <el-table-column
          prop="addr"
          label="操作"
          width="200"
          align="center"
        >
          <template v-slot="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
      />
      <el-dialog
        title="维修人员信息"
        :visible.sync="dialogVisible"
        width="40%"
        :before-close="handleClose"
      >
        <el-form label-position="top" label-width="80px" :model="form2" :inline="true">
          <el-form-item label="姓名">
            <el-input v-model="form2.name" />
          </el-form-item>
          <el-form-item label="工号">
            <el-input v-model="form2.uid" :disabled="true" />
          </el-form-item>

          <el-form-item label="角色">
            <el-radio-group v-model="form2.roles">
              <el-radio label="SystemAdmin" />
              <el-radio label="Maintainer" />
              <el-radio label="PartAdmin" />
            </el-radio-group>
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div style="width: 30%; height: 600px ;float:left;padding-left: 20px">
      <h3 class="vintage">添加用户</h3>
      <el-form ref="form23" label-position="top" label-width="80px" :model="form23" :rules="rules">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form23.name" />
        </el-form-item>
        <el-form-item label="工号" prop="uid">
          <el-input v-model="form23.uid" />
        </el-form-item>
        <!--        <el-form-item label="角色" prop="role">-->
        <!--          <el-input v-model="form23.role"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="角色" prop="roles">
          <el-radio-group v-model="form23.roles">
            <el-radio label="SystemAdmin" />
            <el-radio label="Maintainer" />
            <el-radio label="PartAdmin" />
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="cancel1">取 消</el-button>
        <el-button type="primary" @click="submit1">确 定</el-button>
      </span>

    </div>
  </div>
</template>

<script>
import {
  getAllUserInfo, getUserInfo_name, getUserInfo_uid,
  editUser, saveUser, delUser
} from '@/api/user_manage'
import axios from 'axios'

export default {
  data() {
    const validateNum = (rule, value, callback) => {
      if (!(/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/).test(value)) {
        callback(new Error('请输入用户工号（数字值）'))
      } else {
        callback()
      }
    }
    return {
      value: '',
      vis1: true,
      vis2: false,
      total: 1,
      pageSize: 1,
      isShow1: false,
      dialogVisible: false,
      ImportDialog: false,
      ExportDialog: false,
      actionAddress: process.env.VUE_APP_BASE_API + '/user/import',
      currentPage: 1,
      tableData: [],
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      Form: {
        name: '',
        uid: ''
      },
      Rules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入用户姓名' }
        ],
        uid: [
          { required: true, trigger: 'blur', validator: validateNum }
        ]
      },
      form2: {
        name: '',
        uid: '',
        avatar: '',
        roles: ''
      },
      form23: {
        name: '',
        uid: '',
        avatar: '',
        roles: ''
      },
      rules: {
        name: [
          { required: true, trigger: 'blur', message: '请输入用户姓名' }
        ],
        uid: [
          { required: true, trigger: 'blur', validator: validateNum }
        ],
        roles: [
          { required: true, trigger: 'change', message: '请选择用户角色' }
        ]
      },
      radio: '',
      radio2: ''
    }
  },
  watch: {
    value: {
      deep: true,
      handler: function(newval, oldval) {
        if (newval === '1') {
          this.vis1 = true
          this.vis2 = false
        } else if (newval === '2') {
          this.vis2 = true
          this.vis1 = false
        }
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    getData() {
      getAllUserInfo().then(({ data }) => {
        this.total = data.page.total
        this.pageSize = data.page.size
        this.tableData = data.page.records
        this.Form.name = ''
        this.Form.uid = ''
        this.isShow1 = false
      })
    },
    onSubmit() {
      this.$refs.Form.validate((valid) => {
        if (valid) {
          if (this.vis1 === true) {
            getUserInfo_name(this.Form.name).then(({ data }) => {
              if (data.page.total === 0) {
                this.$message({
                  showClose: true,
                  message: '没有查询到相应的用户信息',
                  type: 'error'
                })
              } else {
                this.total = data.page.total
                this.pageSize = data.page.size
                this.tableData = data.page.records
                this.Form.name = ''
                this.Form.uid = ''
                this.vis2 = false
                this.isShow1 = true
              }
            })
          } else if (this.vis2 === true) {
            getUserInfo_uid(this.Form.uid).then(({ data }) => {
              if (data.page.total === 0) {
                this.$message({
                  showClose: true,
                  message: '没有查询到相应的用户信息',
                  type: 'error'
                })
              } else {
                this.total = data.page.total
                this.pageSize = data.page.size
                this.tableData = data.page.records
                this.Form.name = ''
                this.Form.uid = ''
                this.vis1 = false
                this.isShow1 = true
              }
            })
          }
        }
      })
    },
    handleEdit(row) {
      this.modalType = 1
      this.dialogVisible = true
      this.$nextTick(function() {
        this.form2 = Object.assign(this.form2, row)
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该维修人员信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delUser(row.uid).then(() => {
          this.handleCurrentChange(this.currentPage)
          this.$message({
            type: 'success',
            message: '用户删除成功！'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleCurrentChange(pageNum) {
      getAllUserInfo(pageNum).then(({ data }) => {
        this.total = data.page.total
        this.pageSize = data.page.size
        this.tableData = data.page.records
      })
    },
    handleClose() {
      // 关闭弹窗
      this.dialogVisible = false
      this.ImportDialog = false
      this.ExportDialog = false
    },
    cancel() {
      this.handleClose()
    },
    submit() {
      // 后续对表单的处理
      editUser(this.form2).then(() => {
        // 重新获取当前页列表的接口
        this.handleCurrentChange(this.currentPage)
      })
      // 关闭弹窗
      this.dialogVisible = false
    },
    cancel1() {
      if (this.form23.name !== '' || this.form23.uid !== '' || this.form23.roles !== '') { this.$refs.form23.resetFields() }
      this.$refs.form23.clearValidate()
    },
    submit1() {
      this.$refs.form23.validate((valid) => {
        if (valid) {
          saveUser(this.form23).then(() => {
            this.$message({
              type: 'success',
              message: '用户创建成功！'
            })
            // 重新获取列表的接口
            getAllUserInfo().then(({ data }) => {
              // 跳转到最后一页查看最新添加的记录
              this.currentPage = data.page.pages
            })
          })
        }
      })
    },
    handleImport() {
      this.ImportDialog = true
    },
    handleExport() {
      this.ExportDialog = true
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handlemessage() {
      this.$message({
        type: 'success',
        message: '已成功上传文件'
      })
    }, handleExport1() {
      axios({ // 用axios发送get请求
        method: 'get',
        url: process.env.VUE_APP_BASE_API + '/user/export', // 请求地址
        responseType: 'blob', // 表明返回服务器返回的数据类型
        headers: {
          'Content-Type': 'application/json',
          'getResponse': 'true'
        }
      }).then(res => { // 处理返回的文件流
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })

        const disposition = res.headers['content-disposition']
        const filename = disposition.split(/filename=/i).pop()
        const fileName = decodeURI(filename)

        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL对象
        document.body.removeChild(elink)
      })
    },
    handleExport2() {
      axios({ // 用axios发送get请求
        method: 'get',
        url: process.env.VUE_APP_BASE_API + '/user/extemplate', // 请求地址
        responseType: 'blob', // 表明返回服务器返回的数据类型
        headers: {
          'Content-Type': 'application/json',
          'getResponse': 'true'
        }
      }).then(res => { // 处理返回的文件流
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })

        const disposition = res.headers['content-disposition']
        const filename = disposition.split(/filename=/i).pop()
        const fileName = decodeURI(filename)

        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL对象
        document.body.removeChild(elink)
      })
    }
  }
}
</script>

<style>
.app-container {
  margin: 0 auto;
}

.dialog-footer {
  display: block;
  text-align: center
}

</style>
